import React, {Component} from 'react'

class FetchDownload extends Component {
    download = () => {
        fetch('http://127.0.0.1:3001/file/download').then(res => res.blob().then(blob => {
            let a = document.createElement('a');
            let url = window.URL.createObjectURL(blob);
            let filename = res.headers.get('Content-Disposition');
            if (filename) {
                filename = filename.match(/\"(.*)\"/)[1]; //提取文件名
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
                a = null;
            }
        }));
    };

    render() {
        return (
            <input type="button" value="下载" onClick={this.download}/>
        )
    }
}

export default FetchDownload;

/*
* 原理：
* 1 通过fetch获取文件数据并转成blob格式
* 2 利用window.URL.createObjectURL将blob数据转成对应url进而通过a标签进行访问实现下载
*/